import * as echarts from './echarts';
import WxCanvas from './wx-canvas';

let ctx: any;

Component({
	properties: {
		canvasId: {
			type: String,
			value: 'ec-canvas'
		},

		ec: {
			type: Object
		}
	},

	data: {

	},

	ready() {
		if (!this.data.ec) {
			// tslint:disable-next-line:no-console
			console.warn('组件需绑定 ec 变量，例：<ec-canvas id="mychart-dom-bar" '
				+ 'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>');
			return;
		}

		if (!this.data.ec.lazyLoad) {
			this.init();
		}
	},

	methods: {
		init(this: any, callback?: any) {
			const version = (wx as any).version.version.split('.').map((n: any) => parseInt(n, 10));
			const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9)
				|| (version[0] === 1 && version[1] === 9 && version[2] >= 91);
			if (!isValid) {
				// tslint:disable-next-line:no-console
				console.error('微信基础库版本过低，需大于等于 1.9.91。'
					+ '参见：https://github.com/ecomfe/echarts-for-weixin'
					+ '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82');
				return;
			}

			ctx = (wx as any).createCanvasContext(this.data.canvasId, this);

			const canvas = new WxCanvas(ctx, this.data.canvasId);

			echarts.setCanvasCreator(() => {
				return canvas;
			});

			const query = wx.createSelectorQuery().in(this);
			query.select('.ec-canvas').boundingClientRect<wx.NodesRefRect>((res) => {
				if (typeof callback === 'function') {
					this.chart = callback(canvas, res.width, res.height);
				} else if (this.data.ec && typeof this.data.ec.onInit === 'function') {
					this.chart = this.data.ec.onInit(canvas, res.width, res.height);
				} else {
					this.triggerEvent('init', {
						canvas,
						height: res.height,
						width: res.width
					});
				}
			}).exec();
		},

		canvasToTempFilePath(this: any, opt: any) {
			if (!opt.canvasId) {
				opt.canvasId = this.data.canvasId;
			}

			ctx.draw(true, () => {
				(wx.canvasToTempFilePath as any)(opt, this);
			});
		},

		touchStart(this: any, e: any) {
			if (this.chart && e.touches.length > 0) {
				const touch = e.touches[0];
				this.chart._zr.handler.dispatch('mousedown', {
					zrX: touch.x,
					zrY: touch.y
				});
				this.chart._zr.handler.dispatch('mousemove', {
					zrX: touch.x,
					zrY: touch.y
				});
			}
		},

		touchMove(this: any, e: any) {
			if (this.chart && e.touches.length > 0) {
				const touch = e.touches[0];
				this.chart._zr.handler.dispatch('mousemove', {
					zrX: touch.x,
					zrY: touch.y
				});
			}
		},

		touchEnd(this: any, e: any) {
			if (this.chart) {
				const touch = e.changedTouches ? e.changedTouches[0] : {};
				this.chart._zr.handler.dispatch('mouseup', {
					zrX: touch.x,
					zrY: touch.y
				});
				this.chart._zr.handler.dispatch('click', {
					zrX: touch.x,
					zrY: touch.y
				});
			}
		}
	}
});
